package com.filldream.fastboot.common.util;

import com.filldream.fastboot.common.constant.FinalStr;
import com.filldream.fastboot.common.entity.B;
import com.filldream.fastboot.common.entity.ErrorCode;
import com.filldream.fastboot.common.entity.R;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;

@Service
public class TxOcsUtil {

    @Value("${project.txocs.secretId}")
    private String secretId;

    @Value("${project.txocs.secretKey}")
    private String secretKey;

    @Value("${project.txocs.bucketName}")
    private String bucketName;

    @Value("${project.txocs.regionName}")
    private String regionName;

    /**
     * 图片处理：https://cloud.tencent.com/document/product/436/42215
     * 视频处理：
     * 右下角增加图片水印：?watermark/1/image/aHR0cDovL2V4YW1wbGVzLTEyNTEwMDAwMDQucGljc2gubXlxY2xvdWQuY29tL3NodWl5aW4uanBn/gravity/southeast
     */

    public COSClient init(){
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(regionName);
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    public R<String> uploadFile(MultipartFile file,String filePrefix) {
        //文件后缀
        String suffix = FileIOUtil.getFileSuffix( file.getOriginalFilename() );
        Assert.checkBoolean( FinalStr.okFileSuffixs.contains(suffix.toLowerCase()), ErrorCode.RES_TYPE_DENY.reMsg(suffix) );

        COSClient cosClient = init();
        // 指定要上传到 COS 上对象键
        String key = FileIOUtil.getFileChineseName(filePrefix) + suffix;
        PutObjectRequest putObjectRequest = null;
        try {
            putObjectRequest = new PutObjectRequest(bucketName, key, file.getInputStream(),null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        cosClient.shutdown();
        Date expiration = new Date(new Date().getTime() + 5 * 60 * 10000);
        URL url = cosClient.generatePresignedUrl(bucketName, key, expiration);
        cosClient.shutdown();
        String fileUrl = "https://" + url.getAuthority() + url.getPath();
        return R.autoSuccess(fileUrl).put("urlPrefix",url.getAuthority());
    }

    /**
     * 删除文件
     * @param key	文件名，例如:xxx.jpg
     * @return
     */
    public B delFile(String key) {
        COSClient cosClient = init();
        cosClient.deleteObject(bucketName, key);
        return B.success();
    }

}
